package com.hljx.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hljx.config.exception.DataException;
import com.hljx.entity.SysMenu;
import com.hljx.entity.SysRoleMenuRelation;
import com.hljx.mapper.sys.SysMenuMapper;
import com.hljx.mapper.sys.SysRoleMenuRelationMapper;
import com.hljx.service.SysMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hljx.utils.TreeUtils;
import com.hljx.vo.SysMenuVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 菜单权限表 服务实现类
 * </p>
 *
 * @author gx
 * @since 2023-09-26
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

    @Autowired
    SysRoleMenuRelationMapper sysRoleMenuRelationMapper;

    @Override
    public Boolean saveOrUpdateMenu(SysMenu sysMenu) {
        long count = baseMapper.selectCount(new LambdaQueryWrapper<SysMenu>().eq(SysMenu::getPath, sysMenu.getPath())
                .ne(sysMenu.getId() != null, SysMenu::getId, sysMenu.getId()));
        if(count>0){
            throw new DataException("路由地址重复",201);
        }
        return saveOrUpdate(sysMenu);
    }

    @Override
    public List<SysMenuVO> selectSysMenuVO(String menuName) {
        //是非按菜单名称查询
        QueryWrapper<SysMenu> queryWrapper =new QueryWrapper<>();
        if(StringUtils.isNotBlank(menuName)){
            queryWrapper.lambda().like(SysMenu::getName,menuName);
        }
        //查询所有菜单
        List<SysMenu> menus = this.list(queryWrapper.lambda().orderByAsc(SysMenu::getSortOrder));
        List<SysMenuVO> menuVos = new ArrayList<>();
        menus.forEach(s->{
            SysMenuVO sysMenuVO = new SysMenuVO();
            BeanUtil.copyProperties(s,sysMenuVO);
            menuVos.add(sysMenuVO);
        });
        //生成树形菜单，子节点在children里面
        return TreeUtils.generateTrees(menuVos);
    }

    @Override
    public Boolean remove(Long id) {
        //查询父节点为当前节点的节点
        List<SysMenu> menuList = this.list(Wrappers.<SysMenu>query().lambda().eq(SysMenu::getParentId, id));
        if (CollUtil.isNotEmpty(menuList)) {
            throw new DataException("菜单存在下级节点,删除失败",201);
        }
        sysRoleMenuRelationMapper.delete(Wrappers.<SysRoleMenuRelation>query().lambda().eq(SysRoleMenuRelation::getMenuId, id));
        // 删除当前菜单及其子菜单
        return this.removeById(id);
    }
}
